package tree;

/*
 * This code is based on an example provided by Richard Stanford, 
 * a tutorial reader.
 */
import editor.Editor;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

public class TreePanel extends JPanel {

    private int newNodeSuffix = 1;
    private static String ADD_FILE_COMMAND = "add_file";
    private static String ADD_FOLDER_COMMAND = "add_folder";
    private static String REMOVE_COMMAND = "remove";
    private static String RENAME_COMMAND = "rename";
    private static String CLEAR_COMMAND = "clear";

    java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("editor/bundle/TreeBundle_es_PE"); // NOI18N

    private DynamicTree treePanel;

    JPopupMenu popup;
    JMenuItem mi;
    Editor editor;

    public TreePanel() {
        super(new BorderLayout());
    }

    public TreePanel(Editor editor) {
        super(new BorderLayout());
        this.editor = editor;
        treePanel = new DynamicTree();
    }

    public void setTreeProject(String path) {
        treePanel.setPath(path, editor);

        popup = new JPopupMenu();
        mi = new JMenuItem(bundle.getString("add_file"));
        mi.setActionCommand(ADD_FILE_COMMAND);
        mi.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JTextField txtNameFile = new JTextField();
                Object[] message = {bundle.getString("name_file") + " : ", txtNameFile};
                Icon pie = createImageIcon("img/text-x-generic.png");

                int option = JOptionPane.showConfirmDialog(null, message, bundle.getString("new_file"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, pie);
                if (option == JOptionPane.OK_OPTION) {
                    String path = treePanel.getslastSelected();

                    String path_url = path + File.separator + txtNameFile.getText();

                    File file = new File(path_url);

                    if (file.exists()) {
                        for (;;) {
                            path_url = path_url + "1";
                            file = new File(path_url);
                            if (!file.exists()) {
                                break;
                            }
                        }
                    }
                    try {
                        try (FileWriter fw = new FileWriter(path_url)) {
                            fw.write("");
                        }
                    } catch (IOException ee) {
                        System.out.println("Can't open file '' for writing :: " + path_url);
                        return;
                    }
                    treePanel.addObject(txtNameFile.getText());
                }
            }
        });
        popup.add(mi);

        mi = new JMenuItem(bundle.getString("add_folder"));//"Add Folder"
        mi.setActionCommand(ADD_FOLDER_COMMAND);
        mi.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JTextField txtNameFile = new JTextField();
                Object[] message = {bundle.getString("name_folder"), txtNameFile};//"Name Folder:"
                Icon pie = createImageIcon("img/folder16.png");

                int option = JOptionPane.showConfirmDialog(null, message, bundle.getString("new_folder"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, pie);
                if (option == JOptionPane.OK_OPTION) {
                    String path = treePanel.getslastSelected();

                    String path_url = path + File.separator + txtNameFile.getText();

                    File file = new File(path_url);

                    if (file.exists()) {
                        for (;;) {
                            path_url = path_url + "1";
                            file = new File(path_url);
                            if (!file.exists()) {
                                break;
                            }
                        }
                    }
                    File fw = new File(path_url);
                    fw.mkdir();
                    treePanel.addObject(txtNameFile.getText());
                }
            }
        });
        popup.add(mi);
        popup.addSeparator();

        mi = new JMenuItem(bundle.getString("rename"));//"Rename"
        mi.setActionCommand(RENAME_COMMAND);
        mi.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JTextField txtNameFile = new JTextField();
                Object[] message = {bundle.getString("name_file") + " : ", txtNameFile};
                Icon pie = createImageIcon("img/folder16.png");
                //String path1 = treePanel.getslastSelected();
                String name = treePanel.getslastSelectedName();
                txtNameFile.setText(name);
                int option = JOptionPane.showConfirmDialog(null, message, bundle.getString("rename"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, pie);
                if (option == JOptionPane.YES_OPTION) {
                    String path = treePanel.getslastSelected2();
                    String path_url = treePanel.getslastSelectedParent() + File.separator + txtNameFile.getText();
                    File newName = new File(path);
                    File newName2 = new File(path_url);

                    if (newName.isFile()) {
                        newName.renameTo(newName2);
                        treePanel.changeCurrentNode(txtNameFile.getText());
                    } else {
                        try {
                            //crear direcorio
                            newName2.mkdir();
                            copyFolder(newName, newName2);
                            treePanel.changeCurrentNodeFolder(path_url, path);
                            editor.tab.deletefile(path);
                            editor.tab.closeDelete();
                        } catch (IOException ex) {
                            Logger.getLogger(TreePanel.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }

                }
            }
        });
        popup.add(mi);
        popup.addSeparator();

        mi = new JMenuItem(bundle.getString("rename"));
        mi.setActionCommand(REMOVE_COMMAND);
        mi.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int n = JOptionPane.showConfirmDialog(
                        null,
                        bundle.getString("would_you_like_to_delete"),
                        bundle.getString("delete"),
                        JOptionPane.YES_NO_OPTION);
                if (n == JOptionPane.YES_OPTION) {
                    String path = treePanel.getslastSelectedDelete();
                    try {
                        editor.tab.deletefile(path);
                        treePanel.removeCurrentNode();
                        editor.tab.closeDelete();

                    } catch (Exception ee) {
                        ee.printStackTrace();

                    }
                }
                //Remove button clicked
            }
        });

        popup.add(mi);
        popup.setOpaque(true);
        popup.setLightWeightPopupEnabled(true);

        //Lay everything out.
        treePanel.setPopup(popup);
        treePanel.setPreferredSize(new Dimension(300, 150));
        add(treePanel, BorderLayout.CENTER);
        treePanel.updateUI();
    }

    void rename(String name) {
        treePanel.addObject(name);
    }

    public static void copyFolder(File src, File dest) throws IOException {
        if (src.isDirectory()) {
            //if directory not exists, create it
            if (!dest.exists()) {
                dest.mkdir();
            }
            //list all the directory contents
            String files[] = src.list();
            for (String file : files) {
                //construct the src and dest file structure
                File srcFile = new File(src, file);
                //File destFile = new File(dest + "\\" + src.getName(), file);
                File destFile = new File(dest, file);
                //recursive copy
                copyFolder(srcFile, destFile);
            }
        } else {
            OutputStream out;
            try (InputStream in = new FileInputStream(src)) {
                out = new FileOutputStream(dest);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = in.read(buffer)) > 0) {
                    out.write(buffer, 0, length);
                }
            }
            out.close();
            System.out.println("File copied from " + src + " to " + dest);
        }
    }

    protected final ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = TreePanel.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

    public void clear() {
        treePanel.clear();
        
    }
}
